package com.jason.bookworm.dao.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

//权限校验用到的用户规范
@Data
public class LoginUser implements UserDetails {

    private final User user;

    private final List<String> permissions;

    @JSONField(serialize = false)   //不序列化该对象
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(User user) {
        this.user = user;
        //从user中获取权限
        String privilege = user.getPrivilege();
        permissions=new ArrayList<>();
        switch (privilege){
            case "manager":
                permissions.add("manager");
                permissions.add("reader");
                break;
            case "admin":
                permissions.add("admin");
                permissions.add("manager");
                permissions.add("reader");
                break;
            case "reader":
            default:
                permissions.add("reader");
                break;
        }
    }

    /**
     * 获取用户权限信息
     * @return 用户权限信息封装
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities!=null){
            return this.authorities;
        }
        this.authorities=permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return this.authorities;
    }

    /**
     * 获取密码
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 获取用户名
     */
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    /**
     * 账户是否未过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否未锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 账户整数是否未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账户是否启用
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
